package com.bianxianmao.myinfo.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bianxianmao.MyApplication;
import com.bianxianmao.R;
import com.bianxianmao.utils.Constants;
import com.bianxianmao.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;


/**
 * Created by Administrator on 2017/7/8 0008.
 * 注册
 */

public class RegisterActivity extends Activity implements View.OnClickListener {
    /**
     * 客户端输入的验证码
     */
    private String identifycode;
    /**
     * 服务器端获取的验证码
     */
    private static String serverValicationCode;
    private TextView tvAlreadyRegist;
    private EditText etphone;
    private TextView useagreement;
    private Button getidentify;
    private MyCountDownTimer countDownTimerUtils;
    //密码的正则表达式
    private String reg;
    //手机号的正则表达式
    private String regex;
    private EditText etpwd;
    private EditText etgetidentify;
    private CheckBox checkbox;
    private Button register;
    private CheckBox psdcheckbox;
    private String phone;

    //短信验证码内容 验证码是6位数字的格式
    private String strContent;
    private String patternCoder = "(?<!\\d)\\d{6}(?!\\d)";
    private String mobile;
    private String pwd;
    private String code;
    private boolean checked;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
    }

    //复写倒计时
    class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            getidentify.setClickable(false);
            getidentify.setTextColor(R.color.buttonColor_gray);
            getidentify.setText(l / 1000 + "s秒后重发");
        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            getidentify.setText("重新获取验证码");
            //设置可点击
            getidentify.setClickable(true);
        }
    }

    private void initView() {
        tvAlreadyRegist = (TextView) findViewById(R.id.tv_already_regist);
        etphone = (EditText) findViewById(R.id.et_phone);
        etpwd = (EditText) findViewById(R.id.et_password);
        etgetidentify = (EditText) findViewById(R.id.et_identifycode);
        getidentify = (Button) findViewById(R.id.btn_get_identifycode);
        useagreement = (TextView) findViewById(R.id.tv_user_agreement);
        register = (Button) findViewById(R.id.btn_register);
        checkbox = (CheckBox) findViewById(R.id.checkbox);
        psdcheckbox = (CheckBox) findViewById(R.id.psw_checkbox);

        tvAlreadyRegist.setOnClickListener(this);
        useagreement.setOnClickListener(this);
        getidentify.setOnClickListener(this);
        checkbox.setOnClickListener(this);
        psdcheckbox.setOnClickListener(this);
        register.setOnClickListener(this);
    }

    public void sendmessage() {

        mobile = etphone.getText().toString().trim();
        OkHttpUtils.get().url(Constants.SENDMESSAGEURL + "?mobile=" + mobile + "&type=1").build().execute(new StringCallback() {
            // http://1.migree.com.cn/duobao/userLogin/sendSMSCode.json?mobile=15036180604&type=1
            int type;

            @Override
            public void onError(com.squareup.okhttp.Request request, Exception e) {
                Log.i("ccc", "onError: " + e);
            }

            @Override
            public void onResponse(String response) {
                Log.i(TAG, "onResponse: ---" + response);

            }

        });
    }

    /**
     * 匹配短信中间的6个数字（验证码等）
     *
     * @param patternContent
     * @return
     */
    private String patternCode(String patternContent) {
        if (TextUtils.isEmpty(patternContent)) {
            return null;
        }
        Pattern p = Pattern.compile(patternCoder);
        Matcher matcher = p.matcher(patternContent);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    private void regist() {
        String url = "http://duobao.bianxianmao.comduobao/userLogin/userLogin/phoneRegister.json" + "?mobile=" + mobile + "&smsCode=" + identifycode + "&passWord=" + pwd;
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("aa", "post请求成功" + response);
                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putString("phone", phone);
                editor.putString("password", pwd);
                editor.commit();

                startActivity(new Intent(RegisterActivity.this, SuccessregisterActivity.class));
                Toast.makeText(RegisterActivity.this, "恭喜您注册成功", Toast.LENGTH_SHORT).show();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("aa", "get请求失败" + error.toString());
            }
        });
        request.setTag("volleypost");
        MyApplication.getHttpQueue().add(request);
    }

    @Override
    protected void onStop() {
        super.onStop();
        MyApplication.getHttpQueue().cancelAll("volleyget"); //结束Activity时队列里面注销
        MyApplication.getHttpQueue().cancelAll("volleypost");
    }

    @Override
    public void onClick(View v) {
        //获取手机号
        phone = etphone.getText().toString().toString().trim();
        //获取输入短信验证码
        identifycode = etgetidentify.getText().toString().trim();
        //获取输入密码
        pwd = etpwd.getText().toString();
        boolean phoneresult = Utils.isPhone(phone);
        boolean pwdresult = Utils.isPassword(pwd);
        boolean idetifyresult = Utils.isIdentifycod(identifycode);
        switch (v.getId()) {
            case R.id.btn_get_identifycode://获取验证码

                if (phone.isEmpty()) {
                    Toast.makeText(RegisterActivity.this, "请输入手机号码", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (phoneresult == false) {
                    Toast.makeText(RegisterActivity.this, "输入手机号码不正确", Toast.LENGTH_SHORT).show();
                    break;
                }
                new MyCountDownTimer(60000, 1000).start();
                sendmessage();
                break;
            case R.id.tv_already_regist://已经注册

                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                break;
            case R.id.btn_register://注册
                if (checkbox.isChecked() == false) {
                    register.setClickable(false);
                    break;
                }
                if (phone.isEmpty()) {
                    Toast.makeText(RegisterActivity.this, "请输入手机号码", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (phoneresult == false) {
                    Toast.makeText(RegisterActivity.this, "输入手机号码不正确", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (identifycode.isEmpty()) {
                    Toast.makeText(RegisterActivity.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (pwd.isEmpty()) {
                    Toast.makeText(RegisterActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (pwdresult == false) {
                    Toast.makeText(RegisterActivity.this, "请6-16位密码", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (identifycode.isEmpty()) {
                    Toast.makeText(RegisterActivity.this, "验证码不为空", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (idetifyresult == false) {
                    Toast.makeText(RegisterActivity.this, "验证码格式错误", Toast.LENGTH_SHORT).show();
                    break;
                }
                regist();

                break;
            case R.id.checkbox:

                checked = checkbox.isChecked();
                if (checked == true) {
                    register.setBackgroundResource(R.drawable.btn_regist_bg);
                    register.setClickable(true);
                } else {
                    register.setBackgroundResource(R.drawable.btn_regist_bg_gray);
                    register.setClickable(false);
                }
                break;
            case R.id.psw_checkbox:
                boolean checkedpsw = psdcheckbox.isChecked();
                if (checkedpsw == true) {
                    etpwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    etpwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                break;
            case R.id.tv_user_agreement://用户协议
                startActivity(new Intent(RegisterActivity.this, ServiceagreeActivity.class));
                break;
        }

    }


}
